# coding=utf-8
from  SplitGraph  import DigestionTime
from  SplitGraph  import SplitGraph  
import time
import  os
class ImageServer:
     def __init__(self,argv={}):
         self.argv=argv
     def Init(self):
         argv=self.argv
         SaveFile =argv.get('SaveFile')
         SaveFile=SaveFile.replace('\\','/')
         OrgnalImgFile =argv.get('OrgnalImgFile')
         OrgnalImgFile = OrgnalImgFile.replace('\\', '/')
         DTime=DigestionTime()
         self.traverse(OrgnalImgFile,SaveFile,argv)
         if argv.get('get'):
             print(DTime.end())
             print(argv.get('get'))
             self.Start()
     def Start(self):
         delay=self.argv.get('delay')
         if delay!=None:
             self.argv['delay']=delay+1
         time.sleep(delay) 
         self=ImageServer(self.argv)
         self.Init()
     def traverse(self,OrgnalImgFile,SaveFile,argv={}):
         if not os.path.isdir(SaveFile):
             os.mkdir(SaveFile)
         fs = os.listdir(OrgnalImgFile)
         for _file in fs:
             tmp_OrgnalImgFile = os.path.join(OrgnalImgFile,_file)
             tmp_SaveFile = os.path.join(SaveFile,_file)
             if not os.path.isdir(tmp_OrgnalImgFile):
                 _file=_file.lower()
                 formattype=_file[-4:]
                 if formattype=='.png' or formattype=='.jpg' or formattype=='.tif':
                     tmp_SaveFile = os.path.join(SaveFile,_file.replace('.',"_"))
                     tmp_SaveFile=tmp_SaveFile+'/'
                     if not os.path.isdir(tmp_SaveFile):
                         os.mkdir(tmp_SaveFile)
                     obj={'img':tmp_OrgnalImgFile,'save':tmp_SaveFile,'MinValue':argv.get('MinValue')}
                     try:
                         SplitGraph(obj)
                     except IOError:
                        print("Error:1008")
             else:
                 self.traverse(tmp_OrgnalImgFile,tmp_SaveFile,argv)
